import { AddEditPatient, BindDeviceList, ModalConfirm } from '@/components';
import DeviceListCom from '@/pages/DeviceMsg/list';
import PatientListCom from '@/pages/PatientMsg/list';
import {
  screenAreaBindDeviceOrPatient,
  screenAreaUnbindDeviceOrPatient,
} from '@/services/common';
import { Button, Form, Modal, Popconfirm, message } from 'antd';
import React, { useImperativeHandle, useRef, useState } from 'react';
import './index.less';

const ScreenAreaPatientMsg = React.forwardRef((props: any, ref) => {
  const { refreshList, ecgModuleItem } = props;
  const [form] = Form.useForm<any>();
  const deviceListComRef = useRef<any>(null); // 定义 ref 用于访问子组件的方法和属性
  const patientListComRef = useRef<any>(null); // 定义 ref 用于访问子组件的方法和属性
  const bindDeviceListRef = useRef<any>(null); // 定义 ref 用于访问子组件的方法和属性
  const modalConfirmRef = useRef<any>(null);
  const [modalOpen, setModalOpen] = useState(false);
  const [modItem, setModItem] = useState<any>(null);
  const [patientId, setPatientId] = useState<any>('');
  const [deviceId, setDeviceId] = useState<any>('');
  const [confirmLoading, setConfirmLoading] = useState<boolean>(false);

  const handleModalShow = async (row?: any) => {
    console.log('row', row);
    setModItem(row || null);
    if (!modalOpen) {
      form.resetFields(); // 重置表单
    }
    if (row) {
      form.setFieldsValue({
        ...row,
        parentId: row.parentId != '0' ? row.parentId : null,
      });
      setPatientId(row?.patient?.id || '');
    }
    setModalOpen(!modalOpen);
  };
  const getChildrenSelectData = (type: string, data: any) => {
    if (type === 'patient') {
      setPatientId(data.length > 0 ? data[0] : '');
    } else {
      setDeviceId(data.length > 0 ? data[0] : '');
    }
  };
  const refreshDeviceList = () => {
    deviceListComRef?.current?.refreshList(); // 调用子组件的方法刷新表格数据
    bindDeviceListRef?.current?.refreshList(); // 调用子组件的方法刷新表格数据
  };
  const handleBindScreenArea = () => {
    if (deviceId && patientId) {
      modalConfirmRef?.current?.handleModalShow('确定将该设备绑定该分区?');
    } else {
      modalConfirmRef?.current?.handleModalShow('确定将该患者绑定该分区?');
    }
  };
  const modalSuccessCallback = async () => {
    setConfirmLoading(true);
    if (deviceId && patientId) {
      modalConfirmRef?.current?.handleModalShow('确定将该设备绑定该分区?');
      const res = await screenAreaBindDeviceOrPatient({
        patientId: patientId,
        deviceId: deviceId,
        areaId: modItem?.id,
        bindType: 1, // 1 分区绑定设备 2 分区绑定患者
      });
      if (res?.code === 200) {
        setConfirmLoading(false);
        setModalOpen(!modalOpen);
        refreshList();
      } else {
        setConfirmLoading(false);
      }
    } else {
      modalConfirmRef?.current?.handleModalShow('确定将该患者绑定该分区?');
      const res = await screenAreaBindDeviceOrPatient({
        patientId: patientId,
        deviceId: deviceId,
        areaId: modItem?.id,
        bindType: 2, // 1 分区绑定设备 2 分区绑定患者
      });
      if (res?.code === 200) {
        setConfirmLoading(false);
        setModalOpen(!modalOpen);
        refreshList();
      } else {
        setConfirmLoading(false);
      }
    }
  };
  useImperativeHandle(ref, () => ({
    handleModalShow,
  }));
  return (
    <Modal
      title={<div style={{ fontSize: 20 }}>分区{modItem?.name}</div>}
      open={modalOpen}
      className="screen-area-patient-msg"
      mask={false}
      width={1500}
      footer={[
        <Button key="back" onClick={() => setModalOpen(false)}>
          关闭
        </Button>,
        <Popconfirm
          key="clearDeviceScreen"
          title="确认清空分区设备?"
          onConfirm={async () => {
            const res = await screenAreaUnbindDeviceOrPatient({
              areaId: modItem?.id,
              deviceId: modItem?.device?.id,
              patientId: modItem?.patient?.id,
              unbindType: 1,
            });
            if (res?.code === 200) {
              message.success('操作成功');
              setModalOpen(!modalOpen);
              refreshList();
            }
          }}
          okText="确认"
          cancelText="取消"
        >
          <Button danger disabled={!modItem?.deviceId}>
            清空设备
          </Button>
        </Popconfirm>,
        <Popconfirm
          key="clearScreen"
          title="确认清空该分区?"
          onConfirm={async () => {
            const res = await screenAreaUnbindDeviceOrPatient({
              areaId: modItem?.id,
              deviceId: modItem?.device?.id,
              patientId: modItem?.patient?.id,
              unbindType: 2,
            });
            if (res?.code === 200) {
              message.success('操作成功');
              setModalOpen(!modalOpen);
              refreshList();
            }
          }}
          okText="确认"
          cancelText="取消"
        >
          <Button danger type="primary" disabled={!modItem?.patientId}>
            清空分区
          </Button>
        </Popconfirm>,
        <Button
          key="concatScreen"
          type="primary"
          disabled={!patientId}
          loading={confirmLoading}
          onClick={handleBindScreenArea}
        >
          分区关联
        </Button>,
      ]}
      onCancel={() => setModalOpen(false)}
      destroyOnHidden={true}
      forceRender={true}
    >
      {modalOpen && (
        <div className="main-wrapper">
          <div className="content-wrapper">
            <div className="left">
              {modItem.patientId ? (
                <AddEditPatient
                  ecgModuleItem={ecgModuleItem}
                />
              ) : (
                <PatientListCom
                  from="components"
                  ecgModuleItem={ecgModuleItem}
                  ref={patientListComRef}
                  getChildrenSelectData={getChildrenSelectData}
                />
              )}
            </div>
            <div className="right">
              <BindDeviceList
                ecgModuleItem={ecgModuleItem}
                patientId={patientId}
                ref={bindDeviceListRef}
                refreshDeviceList={refreshDeviceList}
                getChildrenSelectData={getChildrenSelectData}
              />
              <div className="interval"></div>
              <DeviceListCom
                from="components"
                ref={deviceListComRef}
                patientId={patientId}
                refreshDeviceList={refreshDeviceList}
              />
            </div>
          </div>
        </div>
      )}
      {/* 确认弹层 */}
      <ModalConfirm
        ref={modalConfirmRef}
        successCallback={modalSuccessCallback}
      />
    </Modal>
  );
});

export default ScreenAreaPatientMsg;
